package ru.dadle8.service.impl.callback.kbju;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ru.dadle8.model.bot.entity.MessageCallbackData;
import ru.dadle8.model.bot.entity.State;
import ru.dadle8.model.bot.type.CallbackAction;
import ru.dadle8.model.bot.type.CommandState;
import ru.dadle8.service.impl.callback.AbstractCallbackService;

import java.lang.reflect.Field;

@Service
@Slf4j
public class KbjuWaitAnswerCallbackServiceImpl extends AbstractCallbackService {

    @Override
    public int getAction() {
        return CallbackAction.KBJU_ANSWER.getAction();
    }

    @Override
    public void processUpdate(Update update) throws TelegramApiException {
        CallbackQuery callbackQuery = update.getCallbackQuery();
        MessageCallbackData callbackData = getMessageHelper().getMessageCallbackData(callbackQuery);
        Long chatId = callbackQuery.getMessage().getChatId();
        Integer messageId = callbackQuery.getMessage().getMessageId();

        getBot().execute(getMessageHelper().sendEditMessageText(chatId, messageId, getText(callbackQuery)));
        getStorage().updateState(new State(2030, CommandState.KBJU_WAIT_ANSWER, chatId, callbackData.toChatId()));

        // avoid 'loading...'
        getBot().execute(getMessageHelper().sendAnswerCallbackQuery(getCallbackQuery()));

        getBot().execute(getMessageHelper().sendMessage(chatId, "Напишите ответ в следующем сообщении"));
    }

    private String getText(CallbackQuery callbackQuery) {
        // hack
        try {
            // Create Field object
            Field privateField = CallbackQuery.class.getDeclaredField("message");

            // Set the accessibility as true
            privateField.setAccessible(true);

            // Store the value of private field in variable
            Message message = (Message) privateField.get(callbackQuery);
            return message.getText();
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error(e.getMessage());
        }
        // end hack
        return StringUtils.EMPTY;
    }
}
